import {createElement, getDomain} from './utils';
import {renderApiConfigList} from './apiConfigList';
import {renderGlobalHeaders} from './globalHeaders';
import {renderProxyConfigs} from './proxyConfigs';
import {ConfigStore} from '../storage/configStore';
import type {RedirectorConfig} from '../types/config';

export function initConfigPanel() {
    // 创建悬浮按钮
    let floatingBtn = document.getElementById('settingsButton');
    if (!floatingBtn) {
        floatingBtn = createFloatingButton();
        // 因为配置了菜单，暂时注释掉配置按钮入口
        // document.body.appendChild(floatingBtn);
    }

    // 创建模态窗口
    let modal = document.getElementById('configModal');
    if (!modal) {
        modal = createConfigModal();
        document.body.appendChild(modal);
    }

    // 绑定按钮点击事件
    floatingBtn.addEventListener('click', () => {
        modal.classList.add('show');
        floatingBtn.classList.add('hidden');
    });

    // 获取关闭按钮并添加事件监听
    const closeBtn = modal.querySelector('.close-btn') as HTMLElement;
    if (closeBtn) {
        closeBtn.addEventListener('click', () => {
            // 添加关闭动画
            modal.classList.add('closing');

            // 等待动画完成后再隐藏模态框
            setTimeout(() => {
                modal.classList.remove('show', 'closing');
                floatingBtn.classList.remove('hidden');
            }, 250); // 与CSS中的transition时间相匹配
        });
    }

    // 获取导入导出按钮
    const importBtn = modal.querySelector('.import-btn') as HTMLElement;
    const exportBtn = modal.querySelector('.export-btn') as HTMLElement;

    if (importBtn) {
        importBtn.addEventListener('click', () => {
            // 创建文件输入元素
            const fileInput = createElement('input', {
                attrs: {
                    type: 'file',
                    accept: '.json',
                    style: 'display: none;'
                }
            }) as HTMLInputElement;

            // 监听文件选择
            fileInput.addEventListener('change', async () => {
                const file = fileInput.files?.[0];
                if (!file) return;

                try {
                    const text = await file.text();
                    const config = JSON.parse(text) as RedirectorConfig;

                    // 验证配置格式
                    if (!isValidConfig(config)) {
                        alert('配置文件格式不正确');
                        return;
                    }

                    // 保存配置
                    ConfigStore.saveConfig(config);
                    alert('配置导入成功');

                    // 刷新页面以应用新配置
                    window.location.reload();
                } catch (error) {
                    console.error('导入配置失败:', error);
                    alert('导入配置失败，请检查文件格式');
                }
            });

            // 触发文件选择
            fileInput.click();
        });
    }

    if (exportBtn) {
        exportBtn.addEventListener('click', () => {
            try {
                // 获取当前配置
                const config = ConfigStore.getConfig();

                // 创建 Blob
                const blob = new Blob(
                    [JSON.stringify(config, null, 2)],
                    {type: 'application/json'}
                );

                // 创建下载链接
                const url = URL.createObjectURL(blob);
                const link = createElement('a', {
                    attrs: {
                        href: url,
                        download: `request-redirector-config-${getDomain()}-${new Date().toLocaleString()}.json`
                    }
                }) as HTMLAnchorElement;

                // 触发下载
                document.body.appendChild(link);
                link.click();

                // 清理
                document.body.removeChild(link);
                URL.revokeObjectURL(url);
            } catch (error) {
                console.error('导出配置失败:', error);
                alert('导出配置失败');
            }
        });
    }

    // 初始化侧边栏和内容区域
    initSidebar(modal);
}

// 创建悬浮按钮
function createFloatingButton(): HTMLElement {
    const button = createElement('div', {
        attrs: {
            id: 'settingsButton',
            class: 'floating-button',
            title: '配置'
        }
    });

    button.innerHTML = `⚒`;

    return button;
}

// 创建配置模态窗口
function createConfigModal(): HTMLElement {
    const modal = createElement('div', {
        attrs: {
            id: 'configModal',
            class: 'modal'
        }
    });

    modal.innerHTML = `
    <div class="modal-content">
      <div class="modal-header">
        <h2>HTTP请求拦截配置</h2>
        <div class="header-buttons">
          <button class="import-btn">导入配置</button>
          <button class="export-btn">导出配置</button>
          <button class="close-btn"></button>
        </div>
      </div>
      <div class="modal-body">
        <div class="sidebar">
          <ul>
            <li class="active" data-tab="apiConfigPanel">接口配置</li>
            <li data-tab="globalHeadersPanel">全局请求头</li>
            <li data-tab="proxyConfigPanel">代理设置</li>
          </ul>
        </div>
        <div class="content">
          <div class="panel active" id="apiConfigPanel"></div>
          <div class="panel" id="globalHeadersPanel"></div>
          <div class="panel" id="proxyConfigPanel"></div>
    </div>
      </div>
    </div>
  `;

    return modal;
}

// 初始化侧边栏
function initSidebar(modal: HTMLElement) {
    const sidebarItems = modal.querySelectorAll('.sidebar li');
    const panels = modal.querySelectorAll('.panel');

    // 渲染初始内容（接口配置面板）
    const apiConfigPanel = modal.querySelector('#apiConfigPanel') as HTMLElement;
    if (apiConfigPanel) {
        renderApiConfigList(apiConfigPanel);
    }

    // 渲染全局请求头面板
    const globalHeadersPanel = modal.querySelector('#globalHeadersPanel') as HTMLElement;
    if (globalHeadersPanel) {
        renderGlobalHeaders(globalHeadersPanel);
    }

    // 渲染代理设置面板
    const proxyConfigPanel = modal.querySelector('#proxyConfigPanel') as HTMLElement;
    if (proxyConfigPanel) {
        renderProxyConfigs(proxyConfigPanel);
    }

    // 绑定侧边栏点击事件
    sidebarItems.forEach((item) => {
        item.addEventListener('click', () => {
            // 移除所有活动状态
            sidebarItems.forEach(i => i.classList.remove('active'));
            panels.forEach(p => p.classList.remove('active'));

            // 设置当前活动状态
            item.classList.add('active');
            const tabId = (item as HTMLElement).dataset.tab;
            if (tabId) {
                const panel = modal.querySelector(`#${tabId}`);
                if (panel) {
                    panel.classList.add('active');
                }
            }
        });
    });
}

// 验证配置格式
function isValidConfig(config: any): config is RedirectorConfig {
    // 检查基本结构
    if (!config || typeof config !== 'object') return false;

    // 检查必要的属性
    if (!('apiConfig' in config) || !Array.isArray(config.apiConfig)) return false;
    if (!('globalHeaders' in config) || typeof config.globalHeaders !== 'object') return false;
    if (!('proxyConfigs' in config) || !Array.isArray(config.proxyConfigs)) return false;

    // 检查 apiConfig 数组的每个项
    for (const item of config.apiConfig) {
        if (!item.target || !item.replacement) return false;
        if (typeof item.enabled !== 'boolean') return false;
    }

    // 检查 globalHeaders
    for (const [_, value] of Object.entries(config.globalHeaders)) {
        if (!value || typeof value !== 'object') return false;
        if (!('value' in value) || !('enabled' in value)) return false;
        if (typeof (value as any).value !== 'string') return false;
        if (typeof (value as any).enabled !== 'boolean') return false;
    }

    // 检查 proxyConfigs 数组的每个项
    for (const item of config.proxyConfigs) {
        if (!item.url || !item.type) return false;
        if (typeof item.enabled !== 'boolean') return false;
        if (!['global', 'interface'].includes(item.type)) return false;
    }

    return true;
}